const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");
const WebpackShellPluginNext = require("webpack-shell-plugin-next");

const configMap = {
  development: "./config/development.js",
  system: "./config/system.js",
  production: "./config/production.js",
};

module.exports = (env) => {
  const isProduction = env.production === true;
  const configFile = configMap[env.mode || "development"];
  const isDev = process.env.NODE_ENV === "development";

  console.log("Build environment:", {
    mode: env.mode,
    isProduction,
    NODE_ENV: process.env.NODE_ENV,
    configFile,
  });

  return {
    entry: "./server.js",
    target: "node",
    externals: [nodeExternals()],
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "server.bundle.js",
      publicPath: "/",
    },
    mode: isProduction ? "production" : "development",
    watch: isDev,
    watchOptions: {
      ignored: /node_modules/,
      aggregateTimeout: 300,
      poll: 1000,
    },
    devtool: isProduction ? "source-map" : "eval-source-map",
    plugins: [
      new webpack.DefinePlugin({
        "process.env.NODE_ENV": JSON.stringify(
          isProduction ? "production" : "development"
        ),
        // 添加环境标识，帮助运行时判断
        "process.env.WEBPACK_MODE": JSON.stringify(env.mode || "development"),
      }),
      new webpack.NormalModuleReplacementPlugin(/^config$/, function (
        resource
      ) {
        resource.request = path.resolve(__dirname, configFile);
      }),
      ...(isDev
        ? [
            new WebpackShellPluginNext({
              onBuildStart: {
                scripts: ['echo "Starting webpack build..."'],
                blocking: true,
                parallel: false,
              },
              onBuildEnd: {
                scripts: ["nodemon dist/server.bundle.js"],
                blocking: false,
                parallel: true,
              },
            }),
          ]
        : []),
    ],
    resolve: {
      modules: [path.resolve(__dirname, "src"), "node_modules"],
      alias: {
        config: path.resolve(__dirname, configFile), // 直接指向具体的配置文件
      },
      extensions: [".js"],
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
        },
      ],
    },
  };
};
